package com.pg_chat.utils;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import java.sql.SQLOutput;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 为yaml配置文件准备的读取工具
 */
public class YamlPropertiesLoader {

    static Properties properties = null;

    /**
     * 加载yaml文件，使用该工具必须先加载配置文件
     * @param fileName 文件名
     * @return java.util.Properties
     */
    public static Properties yamlLoad(String fileName){
        //从classes文件包中获取配置文件
        Resource resource = new ClassPathResource("/"+fileName);
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        return properties;
    }

    public static Object getCommon(String key) throws Exception{
        if(properties == null){
            throw new Exception("you must load yaml file first!");
        }
        Object objVal = properties.get(key);
        String strVal = objVal instanceof String ?(String) objVal:null;
        if(strVal != null){
            objVal = getSource(strVal);
        }
        return objVal;
    }

    private static Object getSource(String value){
        String regx = "\\$\\{(.+?)\\}";
        String rebuild = "\\$\\{|\\}";
        String tmpVal = "";
        String source = "";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(value);

        while(matcher.find()){
            tmpVal = matcher.group();
            source = tmpVal.replaceFirst(rebuild,"");
            try {
                source = (String)getCommon(source);
            } catch (Exception e) {
                e.printStackTrace();
            }

            value = value.replaceAll(tmpVal,source);
        }
       return value;
    }
}
